package com.greentreecs.fms.pojo.response;

import com.greentreecs.fms.constant.ExceptionConstant;
import com.greentreecs.fms.exception.BadParamException;
import lombok.Data;

import java.sql.SQLException;

/**
 * @author 刀氏春秋
 * @date 2023/12/8
 */
@Data
public class GeneralResponse<T> {
    private String code;
    private String message;
    private T content;

    /**
     * 填充响应体
     *
     * @param content 响应体内容实体
     */
    public void fillResponseWith(T content) {
        if (content != null) {
            this.code = ExceptionConstant.SUCCESS;
            this.message = ExceptionConstant.SUCCESS_MESSAGE;
        } else {
            this.code = ExceptionConstant.COMMON_FAILURE;
            this.message = ExceptionConstant.COMMON_FAILURE_MESSAGE;
        }
        this.content = content;
    }

    public void fillResponseByException(Exception e) {
        if (e instanceof BadParamException) {
            this.code = ExceptionConstant.BAD_PARAM;
            this.message = ExceptionConstant.BAD_PARAM_MESSAGE;
        } else if (e instanceof SQLException) {
            this.code = ExceptionConstant.SQL_FAILURE;
            this.message = ExceptionConstant.SQL_FAILURE_MESSAGE;
        } else {
            this.code = ExceptionConstant.COMMON_FAILURE;
            this.message = ExceptionConstant.COMMON_FAILURE_MESSAGE;
        }
    }
}
